﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml;

namespace ontheroad
{
    public partial class trfCongestion : PhoneApplicationPage
    {
        private List<trafficCongestion> linkList;

        public trfCongestion()
        {
            InitializeComponent();
            getAllLinkInfo();
            //getFavCongestion();
        }

        public void getAllLinkInfo()
        {
            WebClient wcf = new WebClient();
            linkList = new List<trafficCongestion>();
            Uri uri = new Uri("http://athena.traffy.in.th/apis/apitraffy.php?format=XML&api=getLinkALLInfo&key="
                + App.traf.sessionkey + "&appid=" + App.traf.appid);
            wcf.DownloadStringAsync(uri);
            wcf.DownloadStringCompleted += (s, e) =>
            {
                try
                {
                    getCongestion(e.Result);
                }
                catch (WebException)
                {
                    MessageBox.Show("Please check your internet connection.");
                    NavigationService.GoBack();
                }
            };
        }

        public void getCongestion(string e)
        {
            XElement elm;
            try
            {
                elm = XElement.Parse(e);
            }
            catch (Exception)
            {
                MessageBox.Show("Server connection failed, Please wait a minute and try again.");
                NavigationService.GoBack();
                return;
            }
            while (elm.FirstNode != null)
            {
                string roadname = ((elm.FirstNode as XElement).FirstNode as XElement).FirstAttribute.Value;
                trafficCongestion cgc = new trafficCongestion();
                cgc.road.linkID = (elm.FirstNode as XElement).FirstAttribute.Value;
                cgc.road.startNode = (((elm.FirstNode as XElement).FirstNode as XElement).NextNode as XElement).FirstAttribute.Value;
                cgc.road.endNode = ((((elm.FirstNode as XElement).FirstNode as XElement).NextNode as XElement).NextNode as XElement).FirstAttribute.Value;
                cgc.road.roadName = roadname;
                linkList.Add(cgc);
                elm.FirstNode.Remove();
            }
            WebClient wcf2 = new WebClient();

            string uri2name = "http://api.traffy.in.th/apis/apitraffy.php?format=XML&api=getCL&key="
                + App.traf.sessionkey + "&appid=" + App.traf.appid + "&linkid=";

            for (int i = 0; i < linkList.Count; i++)
                uri2name += linkList[i].road.linkID + ((i + 1 == linkList.Count ? "" : ","));
            Uri uri2 = new Uri(uri2name);
            wcf2.DownloadStringAsync(uri2);
            wcf2.DownloadStringCompleted += (s1, e1) =>
            {
                getPCL(e1.Result);
            };
        }

        public void getPCL(string e)
        {
            try
            {
                XElement elm2 = XElement.Parse(e);
                while (elm2.FirstNode != null)
                {
                    string linkid = ((elm2.FirstNode as XElement).FirstNode as XElement).Value;
                    int i;
                    for (i = 0; linkList[i].road.linkID != linkid; i++) ;
                    trafficCongestion cgc = linkList[i];
                    cgc.timeCongestion = Convert.ToDateTime((((elm2.FirstNode as XElement).FirstNode as XElement).NextNode as XElement).Value);
                    string conType = ((((elm2.FirstNode as XElement).FirstNode as XElement).NextNode as XElement).NextNode as XElement).Value;
                    switch (conType)
                    {
                        case "H": cgc.congestionType = "ติดขัด"; cgc.statuscolor = new SolidColorBrush(Color.FromArgb(255,230,20,0)); break;
                        case "M": cgc.congestionType = "หนาแน่น"; cgc.statuscolor = new SolidColorBrush(Color.FromArgb(255,239, 150, 8)); break;
                        default: cgc.congestionType = "คล่องตัว"; cgc.statuscolor = new SolidColorBrush(Color.FromArgb(255, 140, 190, 41)); break;
                    }
                    elm2.FirstNode.Remove();
                }
                //MessageBox.Show("");
                WebClient wcf3 = new WebClient();
                string uri3name = "http://api.traffy.in.th/apis/apitraffy.php?api=getPCL&appid="
                    + App.traf.appid + "&key=" + App.traf.sessionkey + "&linkid=";
                for (int i = 0; i < linkList.Count; i++)
                    uri3name += linkList[i].road.linkID + ((i + 1 == linkList.Count ? "" : ","));
                uri3name += "&format=XML";
                Uri uri3 = new Uri(uri3name);
                wcf3.DownloadStringAsync(uri3);
                wcf3.DownloadStringCompleted += (s2, e2) =>
                {
                    try
                    {
                        for (int i = 0; i < linkList.Count; i++)
                        {
                            linkList[i].preCongestionType = "ไม่สามารถระบุได้";
                            linkList[i].predictStatusColor = new SolidColorBrush(Color.FromArgb(255, 153, 153, 153)); 
                        }
                        XElement elm3 = XElement.Parse(e2.Result);

                        while (elm3.FirstNode != null)
                        {
                            string linkid = ((elm3.FirstNode as XElement).FirstNode as XElement).Value;
                            int i;
                            for (i = 0; linkList[i].road.linkID != linkid; i++) ;
                            trafficCongestion cgc = linkList[i];
                            string conType = (((((elm3.FirstNode as XElement).FirstNode as XElement).NextNode as XElement).NextNode as XElement).NextNode as XElement).Value;
                            SolidColorBrush c;
                            switch (Convert.ToInt32(conType))
                            {
                                case 1: conType = "เคลื่อนตัวได้ดี"; c = new SolidColorBrush(Color.FromArgb(255, 140, 190, 41)); break;
                                case 2: conType = "เคลื่อนตัวได้เรื่อยๆ"; c = new SolidColorBrush(Color.FromArgb(255, 140, 190, 41)); break;
                                case 3: conType = "เคลื่อนตัวได้ตามจังหวะสัญญาณไฟ"; c = new SolidColorBrush(Color.FromArgb(255, 140, 190, 41)); break;
                                case 4: conType = "เคลื่อนตัวได้ตามปกติ"; c = new SolidColorBrush(Color.FromArgb(255, 140, 190, 41)); break;
                                case 5: conType = "เคลื่อนตัวช้า"; c = new SolidColorBrush(Color.FromArgb(255, 239, 150, 8)); break;
                                case 6: conType = "หนาแน่น"; c = new SolidColorBrush(Color.FromArgb(255, 239, 150, 8)); break;
                                case 7: conType = "ติดขัด"; c = new SolidColorBrush(Color.FromArgb(255, 230, 20, 0)); break;
                                default: conType = "ไม่สามารถระบุได้"; c = new SolidColorBrush(Color.FromArgb(255, 153, 153, 153)); break;
                            }
                            cgc.preCongestionType = conType;
                            cgc.predictStatusColor = c;
                            elm3.FirstNode.Remove();
                        }
                    }
                    catch (Exception) { }
                    getFavCongestion();
                };
            }
            catch (Exception) { getFavCongestion(); }
        }

        private void getFavCongestion()
        {
            List<int> idList = new List<int>();
            try
            {
                IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("congestiontest.xaml", FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {    //Visualize the text data in a TextBlock text
                    XElement eld = XElement.Parse(reader.ReadToEnd());
                    //MessageBox.Show("");
                    while (eld.FirstNode as XElement != null)
                    {
                        int idAdd = Convert.ToInt32((eld.FirstNode as XElement).Value);
                        (eld.FirstNode as XElement).Remove();
                        idList.Add(idAdd);
                    }
                }
            }
            catch (Exception)
            {
            }

            List<trafficCongestion> conFav = new List<trafficCongestion>();


            for (int i = 0; i < linkList.Count; i++)
                if (idList.Contains(Convert.ToInt32(linkList[i].road.linkID)))
                    conFav.Add(linkList[i]);

            if (conFav.Count != 0)
                noticeMsgFav.Visibility = Visibility.Collapsed;
            else
                noticeMsgFav.Visibility = Visibility.Visible;
            favListbox.ItemsSource = conFav;

            waitScr.Visibility = Visibility.Collapsed;

        }

        private void searchroadbut_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            setSearchCongestion();
        }

        private void setSearchCongestion()
        {
            string roadName = searchroadtxtbox.Text;

            List<trafficCongestion> cfc = new List<trafficCongestion>();

            for (int i = 0; i < linkList.Count; i++)
                if (linkList[i].road.roadName.Contains(roadName) || linkList[i].road.startNode.Contains(roadName)
                    || linkList[i].road.endNode.Contains(roadName))
                    cfc.Add(linkList[i]);
            noticeMsgSearch.Visibility = Visibility.Collapsed;
            if (cfc.Count != 0)
                noticeMsgNotFound.Visibility = Visibility.Collapsed;
            else
                noticeMsgNotFound.Visibility = Visibility.Visible;
            congestionList.ItemsSource = cfc;
        }

        private void addtofav_Click(object sender, System.EventArgs e)
        {
            MessageBoxResult m = MessageBox.Show("add to favorites", "Confirm ?", MessageBoxButton.OKCancel);
            if (m == MessageBoxResult.OK)
            {
                int id = Convert.ToInt32((sender as Button).Tag.ToString());
                string fileName = "congestiontest.xaml";
                XElement elm;
                try
                {
                    IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                    IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        string readString = reader.ReadToEnd();
                        if (readString.Contains("<id>" + id + "</id>"))
                        {
                            MessageBox.Show("Already exists.");
                            return;
                        }
                        elm = XElement.Parse(readString);
                    }


                    List<int> idList = new List<int>();
                    while (elm.FirstNode as XElement != null)
                    {
                        int idAdd = Convert.ToInt32((elm.FirstNode as XElement).Value);
                        (elm.FirstNode as XElement).Remove();
                        idList.Add(idAdd);
                    }

                    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
                    {
                        XmlWriterSettings settings = new XmlWriterSettings();
                        settings.Indent = true;
                        using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                        {
                            writer.WriteStartElement("congestion");
                            writer.WriteStartElement("id");
                            writer.WriteString(id.ToString());
                            writer.WriteEndElement();
                            for (int i = 0; i < idList.Count; i++)
                            {
                                writer.WriteStartElement("id");
                                writer.WriteString(idList[i].ToString());
                                writer.WriteEndElement();
                            }
                            writer.WriteEndElement();
                            writer.WriteEndDocument();
                            writer.Flush();
                        }
                    }

                }
                catch (Exception)
                {
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
                        {
                            XmlWriterSettings settings = new XmlWriterSettings();
                            settings.Indent = true;
                            using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                            {
                                writer.WriteStartElement("congestion");
                                writer.WriteStartElement("id");
                                writer.WriteString(id.ToString());
                                writer.WriteEndElement();
                                writer.WriteEndElement();
                                // Ends the document
                                writer.WriteEndDocument();
                                // Write the XML to the file.
                                writer.Flush();
                            }
                        }
                    }
                }
                getFavCongestion();
            }
        }

        private void delfromfav_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            MessageBoxResult result = MessageBox.Show("Delete from favorites", "Confirm?", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                int id = Convert.ToInt32((sender as Button).Tag.ToString());

                string fileName = "congestiontest.xaml";
                XElement elm;
                IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    string readString = reader.ReadToEnd();
                    elm = XElement.Parse(readString);
                }


                List<int> idList = new List<int>();
                while (elm.FirstNode as XElement != null)
                {
                    int idAdd = Convert.ToInt32((elm.FirstNode as XElement).Value);
                    (elm.FirstNode as XElement).Remove();
                    if (idAdd != id)
                        idList.Add(idAdd);
                }

                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
                {
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                    {
                        writer.WriteStartElement("congestion");
                        for (int i = 0; i < idList.Count; i++)
                        {
                            writer.WriteStartElement("id");
                            writer.WriteString(idList[i].ToString());
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                        writer.Flush();
                    }
                }
                getFavCongestion();
            }
            
        }

        private void searchroadtxtbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			if (e.Key == Key.Enter)
            {
                setSearchCongestion();
            }
        }

        private void refreshBtn_Click(object sender, System.EventArgs e)
        {
        	// TODO: Add event handler implementation here.
            waitScr.Visibility = Visibility.Visible;
            getAllLinkInfo();
            
        }

        
    }
}
